package com.jnu.bookkeep.Data;

import android.content.Context;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class DataStorage {
    public static final String HOLDER_NAME = "data";
    private final Context context;
    List<Bill> billList;
    public DataStorage(Context context) {
        this.context = context;
    }

    @SuppressWarnings("unchecked")
    public List<Bill> loadData(){
        billList = new ArrayList<>();
        try{
            ObjectInputStream objectInputStream = new ObjectInputStream(context.openFileInput(HOLDER_NAME));
            billList = (ArrayList<Bill>)objectInputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return billList;
    }

    public void SaveData() {
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(context.openFileOutput(HOLDER_NAME, Context.MODE_PRIVATE));
            objectOutputStream.writeObject(billList);
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (objectOutputStream != null)
                    objectOutputStream.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
